﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace FluentETL.Impl
{
    public class OleDbSource : OleDbBase, ISource
    {
        public OleDbSource FromTable(string tableName)
        {
            this.CommandText = tableName;
            this.CommandType = CommandType.TableDirect;
            return this;
        }

        public OleDbSource FromQuery(string query)
        {
            this.CommandText = query;
            this.CommandType = CommandType.Text;
            return this;
        }

        public OleDbSource FromStoredProcedure(string storedProc)
        {
            this.CommandText = storedProc;
            this.CommandType = CommandType.StoredProcedure;
            return this;
        }

        public OleDbSource Connection(string connString)
        {
            this.ConnectionString = connString;
            return this;
        }

        public OleDbSource Connection(OleDbConnection conn)
        {
            this.ConnectionObject = conn;
            return this;
        }

        void ISource.InTransformContext(ITransform t, Action action)
        {
            action();
        }

        IEnumerable<IRow> ISource.Rows
        {
            get
            {
                IEnumerable<IRow> rows = base.WithConnectionEnumerate<IRow>(conn => GetRows(conn));
                foreach (var r in rows)
                {
                    yield return r;
                }
            }
        }

        private IEnumerable<IRow> GetRows(OleDbConnection conn)
        {
            OleDbCommand cmd = base.GetSelectCommand(conn);
            IDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                yield return new DataReaderRow(rdr);
            }
        }
    }
}
